/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package readfilesthrowsio;

import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.Reader;
import java.io.Writer;
import java.util.Scanner;

/**
 *
 * @author SONGOKU20
 */
public class ReadFilesThrowsIO {

    /**
     * @param args the command line arguments
     */
    public static String ReadFiles(String Name) throws IOException {
        FileInputStream file=new FileInputStream(Name);
        Reader r=new java.io.InputStreamReader(file,"UTF-8");
        //Su dung try & catch de bat loi trong khi doc file
        try{
        BufferedReader br=new BufferedReader(r);
        String s=null;
        StringBuilder line=new StringBuilder();
        /*Doan chuong trinh doc file theo dong*/
        while((s=br.readLine())!=null){
            line.append(s).append("\n");
        }
            System.out.println("Noi dung file la: ");
            System.out.println(line);//in ra noi dung cua file da doc
        return line.toString();
        }
        catch(Exception e){
            System.out.println("Chuong trinh khong the doc file!!!!!!!"+e);
        }
        return "Doc Files thanh cong!!!!";
    }
    public static boolean WriteFiles(String FileName,boolean b) throws FileNotFoundException, IOException{
        Scanner input1=new Scanner(System.in);
        String lin;
        System.out.println("Nhap vao doan can them vao van ban: ");
        lin=input1.nextLine();
        try{
        FileOutputStream files=new FileOutputStream(FileName);
        try(
            Writer w=new java.io.OutputStreamWriter(files,"UTF-8")){    
            w.write(lin);
        }
        return true;
        }
        catch(Exception e){
            System.out.println("Ghi file khong thanh cong!!!!!!!!!");
        }
        return false;
    }
    public static void main(String[] args) throws IOException {
        // TODO code application logic here
        Scanner input=new Scanner(System.in);
        System.out.println("Nhap dau vao cua files: ");
        String Name=input.nextLine();
        ReadFiles(Name);
        System.out.println("Nhap ten file dau ra: ");
        String FileName=input.nextLine();
        WriteFiles(FileName,true);
        ReadFiles(FileName);
    }
}
